package com.rtmart.image.controller;

import com.rtmart.image.utils.FileTools;
import com.rtmart.image.utils.ResponseBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class Index {
    @Value("${image.location}")
    private String indexImagePath;

    @GetMapping("/imageList/{type}")
    public ResponseBuilder indexImageList(@PathVariable String type){
        List<String> allFileName = FileTools.imageUrlList(new File(indexImagePath));
        return ResponseBuilder.build(ResponseBuilder.Code.SUCCESS, allFileName.stream().filter(s -> s.startsWith(type + "-")).collect(Collectors.toList()));
    }

    @DeleteMapping("/admin/image/{fileName}")
    public ResponseBuilder deleteIndexImage(@PathVariable String fileName){
        if (FileTools.deleteFile(new File(indexImagePath + fileName))){
            return ResponseBuilder.build(ResponseBuilder.Code.SUCCESS);
        } else {
            return ResponseBuilder.build(ResponseBuilder.Code.ERROR);
        }
    }

    @PostMapping("/admin/{type}")
    public ResponseBuilder postIndexImage(@PathVariable String type, @RequestParam("file") List<MultipartFile> fileList){
        //建立目录
        File filePath = new File(indexImagePath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        //上传文件
        for (MultipartFile tempFile : fileList) {
            if (tempFile.isEmpty()) continue;
            String imageFileFullPath = indexImagePath + type + "-" + tempFile.getOriginalFilename();
            File file = new File(imageFileFullPath);
            if (file.exists()) {
                for (int i = 1; i <= 100000; i++) {
                    imageFileFullPath = indexImagePath + type + "-" + i + tempFile.getOriginalFilename();
                    file = new File(imageFileFullPath);
                    if (!file.exists()) break;
                }
            }
            FileTools.savaFile(tempFile, file);
        }
        return ResponseBuilder.build(ResponseBuilder.Code.SUCCESS);
    }
}
